package com.kaili.db.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.client.service.ILoginUserInfoService;
import com.kaili.common.OperationType;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.stock.StockInfoBean;
import com.kaili.common.util.SnowflakeIdFactory;
import com.kaili.db.mapper.HsEwbsSignMapper;
import com.kaili.db.service.*;
import com.kaili.except.ResponseStatus;
import com.kaili.pojo.dto.finance.FinSign;
import com.kaili.pojo.dto.sign.SignAddDTO;
import com.kaili.pojo.entity.HsEwbsSign;
import com.kaili.pojo.entity.HsEwbsSignDetail;
import com.kaili.pojo.entity.HsOptEwb;
import com.kaili.pojo.entity.HsOptQuery;
import com.kaili.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.kaili.except.ResponseStatus.SIGN_ADD_DUPLICATE;
import static com.kaili.except.ResponseStatus.SIGN_ADD_ERR;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cgm
 * @since 2018-05-08
 */
@Service
@Transactional
public class HsEwbsSignServiceImpl extends ServiceImpl<HsEwbsSignMapper, HsEwbsSign> implements IHsEwbsSignService {

    @Autowired
    private ILoginUserInfoService loginUserInfoService;
    @Autowired
    private IHsBasicSeqService seqService;
    @Autowired
    private IHsOptEwbService ewbService;
    @Autowired
    private IHsEwbsSignDetailService signDetailService;
    @Autowired
    private IHsOptQueryService queryService;
    @Autowired
    private IHsEwbSubStockService stockService;

    /**
     * 创建签收数据
     *
     * @param signAddDTO
     * @return
     */
    public int createSignDate(SignAddDTO signAddDTO) throws BaseExcept {
        List<FinSign> finSignList = new ArrayList<>();
        List<HsEwbsSignDetail> lst = signAddDTO.getLst();
        if(lst==null || lst.size()<1){
            return -1;
        }
        HsEwbsSign ewbsSign = new HsEwbsSign();
        BeanUtils.copyProperties(signAddDTO, ewbsSign);
        ewbsSign.setCreatedTime(DateUtils.getCurrentDate());
        ewbsSign.setSignNo(seqService.seqByType("SG"));
        ewbsSign.setOperationId(String.valueOf(SnowflakeIdFactory.getNextId()));
        ewbsSign.setRdStatus(1);
        baseMapper.insert(ewbsSign);
        List<HsEwbsSignDetail> details = new ArrayList<>();

        List<HsOptQuery> queries = new ArrayList<>();
        for (HsEwbsSignDetail detail : lst) {
            HsOptEwb ewb = ewbService.getEWbByEwbNo(detail.getEwbNo());
            if (ewb == null) {
                throw new BaseExcept(ResponseStatus.EWB_NOT_EXISTS, detail.getEwbNo());
            }
            if (ewb.getIsSign() == 1) {
                throw new BaseExcept(ResponseStatus.ALREADY_SIGNED_ERR, detail.getEwbNo());
            }
            //已经从数据库SQL查询过滤到件不全的单号了,所以这里屏蔽掉
//            if (ewb.getPickGoodsModeId() == OperationType.PICK_MODE_DISPATCH) {
//                if (ewb.getTotalPiece() != stockService.getStockBySiteId(sign.getSiteId(), detail.getEwbNo(), OperationType.STOCK_DISPATCH_ON_THE_WAY)) {
//                    throw new BaseExcept(SIGN_STOCK_NOT_ENOUGH_ERR, detail.getEwbNo());
//                }
//            } else if (ewb.getPickGoodsModeId() == OperationType.PICK_MODE_SELF) {
//                if (ewb.getTotalPiece() != stockService.getStockBySiteId(sign.getSiteId(), detail.getEwbNo(), OperationType.STOCK_ON)) {
//                    throw new BaseExcept(SIGN_STOCK_NOT_ENOUGH_ERR, detail.getEwbNo());
//                }
//            }

            if (ewbService.doSignByEwb(detail.getEwbNo()) == 0) {
                throw new BaseExcept(SIGN_ADD_ERR);
            }

            //System.out.println("update value:"+ewbService.doSignByEwb(detail.getEwbNo()));
            detail.setCreatedTime(DateUtils.getCurrentDate());
            detail.setDeviceCode(ewbsSign.getDeviceCode());
            detail.setScanSourceId(ewbsSign.getScanSourceId());
            detail.setSignNo(ewbsSign.getOperationId());
            if (signDetailService.hasSigned(detail)) {
                throw new BaseExcept(SIGN_ADD_DUPLICATE);
            }
            details.add(detail);
            StockInfoBean stockInfoBean = new StockInfoBean();
            stockInfoBean.setSize(detail.getPiece());
            stockInfoBean.setSiteId(detail.getSiteId());
            stockInfoBean.setEwbNo(detail.getEwbNo());
            stockInfoBean.setSize(ewb.getTotalPiece());
            //提货方式id   派送  自提
            stockInfoBean.setPickGoodsModeId(ewb.getPickGoodsModeId());
            stockService.signEwbByBs(stockInfoBean);
            HsOptQuery query = new HsOptQuery();
            query.setEwbNo(detail.getEwbNo());
            query.setStep(OperationType.SIGNING);
            query.setOperationTime(DateUtils.getCurrentDate());
            query.setOperationId(ewbsSign.getOperationId());
            query.setOperationSiteId(ewbsSign.getSiteId());
            query.setOperator(ewbsSign.getCreatedBy());
            queries.add(query);


            FinSign finSign = new FinSign();
            finSign.setOperation_id(ewbsSign.getOperationId());
            finSign.setCod_charge(ewb.getCodCharge().doubleValue());
            finSign.setCreated_by(ewbsSign.getCreatedBy());
            finSign.setCreated_time(ewbsSign.getCreatedTime());
            finSign.setEwb_no(detail.getEwbNo());
            if (ewb.getPickGoodsModeId() == 105) {
                finSign.setSend_charge(ewb.getSendCharge().doubleValue());
            } else {
                finSign.setSelf_charge(ewb.getSendCharge().doubleValue());
            }
            finSign.setSend_site_id(ewb.getSendSiteId());
            finSign.setDispatch_site_id(ewb.getDispatchSiteId());
            finSign.setOperate_type("1");
            finSign.setRemark(ewb.getRemark());
            finSignList.add(finSign);
            //finSign.setDispatch_site_id();

        }
        signDetailService.insertBatch(details);
        queryService.insertBatch(queries);
        /*-------------调用财务接口------------------*/
        Map info = new HashMap<>();
        info.put("info", JSON.toJSONString(finSignList));
        stockService.pFinDispatchInput(info);
        return 0;
    }

    @Override
    public int createSignDateByBS(SignAddDTO sign) throws BaseExcept {
        sign.setDeviceCode("BS");
        sign.setCreatedBy(loginUserInfoService.getLoginUserId());
        sign.setScanSourceId(sign.getScanSourceId());
        List<HsEwbsSignDetail> lst = sign.getLst();
        for (HsEwbsSignDetail detail : lst) {
            detail.setScanTime(sign.getSignTime());
            detail.setDeviceCode("BS");
            detail.setScanSourceId(sign.getScanSourceId());
            detail.setSiteId(sign.getSiteId());
            detail.setScanBy(sign.getCreatedBy());
        }
        return createSignDate(sign);
    }

}
